/*********************************************************************************
*
* Copyright (c) ReflectSoftware, Inc. All rights reserved. 
*
* See License.rtf in the solution root for license information.
*
**********************************************************************************/

using System;
using System.Collections.Generic;
using System.Net.Mail;

using ReflectSoftware.Insight.Common;
using ReflectSoftware.Insight.Common.Data;

using RI.Utils.Strings;
using RI.System.Configuration;

namespace ReflectSoftware.Insight.Listeners
{
    internal class ListenerEmail : IReflectInsightListener
	{
        private String ToAddresses { get; set; }
        private String CcAddresses { get; set; }
        private String BccAddresses { get; set; }
        private String Subject { get; set; }
        private String Body { get; set; }
        private Boolean IsHtml { get; set; }
        private MailPriority Priority { get; set; }
        
        //---------------------------------------------------------------------
        /// <summary>
        /// Updates the parameter variables.
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <exception cref="ReflectSoftware.Insight.Common.ReflectInsightException">
        /// </exception>
        public void UpdateParameterVariables(IListenerInfo listener)
        {
            String details = listener.Params["details"];
            if (StringHelper.IsNullOrEmpty(details))
                throw new ReflectInsightException(String.Format("Missing details parameter for listener: '{0}' using details: '{1}'.", listener.Name, listener.Details));

            String configFile = ReflectInsightConfig.LastConfigFullPath;
            String xPath = String.Format("./configuration/insightSettings/emailDetails/details[@name='{0}']", details);
            using (ConfigContainer config = new ConfigContainer(false, configFile, xPath))
            {                
                if(!config.Node.IsSectionSet)
                    throw new ReflectInsightException(String.Format("Cannot find Email Details node '{0}' in configuration file: '{1}'.", details, configFile));

                ToAddresses = config.Node.GetNodeInnerText("toAddresses", String.Empty).Replace(";", ",");
                if (StringHelper.IsNullOrEmpty(ToAddresses))
                    throw new ReflectInsightException(String.Format("toAddresses node text value for Email Details '{0}' in configuration file: '{1}', is required.", details, configFile));


                CcAddresses = config.Node.GetNodeInnerText("ccAddresses", String.Empty).Replace(";", ",");
                BccAddresses = config.Node.GetNodeInnerText("bccAddresses", String.Empty).Replace(";", ",");
                Subject = config.Node.GetNodeInnerText("subject");
                Body = config.Node.GetNodeInnerText("body");
                IsHtml = config.Node.GetNodeInnerText("IsHtml").Trim().ToLower() == "true";

                String sPriority = config.Node.GetNodeInnerText("priority").ToLower().Trim();
                Priority = MailPriority.Normal;
                if (sPriority == "high")
                    Priority = MailPriority.High;
                else if (sPriority == "low")
                    Priority = MailPriority.Low;
            }                    
        }
        //---------------------------------------------------------------------
        /// <summary>
        /// Receives the specified messages.
        /// </summary>
        /// <param name="messages">The messages.</param>
        public void Receive(ReflectInsightPackage[] messages)
        {
            #if NET20
            SmtpClient client = new SmtpClient();
            #else
            using (SmtpClient client = new SmtpClient())
            #endif
            {
                foreach (ReflectInsightPackage package in messages)
                {
                    String details = String.Empty;
                    if (package.IsDetail<DetailContainerString>())
                    {
                        details = package.GetDetails<DetailContainerString>().FData;
                        if (IsHtml)
                        {
                            details = details.Replace(Environment.NewLine, "<br/>");
                        }
                    }

                    using (MailMessage email = new MailMessage())
                    {
                        email.IsBodyHtml = IsHtml;
                        email.Priority = Priority;
                        email.To.Add(ToAddresses);
                        email.Subject = RIUtils.PrepareString(Subject, package, String.Empty);
                        email.Body = RIUtils.PrepareString(Body, package, details);
                        
                        if (!StringHelper.IsNullOrEmpty(CcAddresses)) email.CC.Add(CcAddresses);
                        if (!StringHelper.IsNullOrEmpty(BccAddresses)) email.Bcc.Add(CcAddresses);

                        #if NET45
                        client.SendAsync(email, null);
                        #else
                        client.Send(email);
                        #endif
                    }
                }
            }
        }
	}
}
